<template>
  <!-- 发布商品之前的弹窗 -->
  <div class="add_before">
    <el-dialog :title="title" :visible.sync="dialogVisible" append-to-body :close-on-click-modal="false" width="500px" @close="close" :close-on-press-escape="false">
      <div class="add_before_box new_form_box">
        <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="80px" class="demo-ruleForm">
          <div style="margin-bottom: 10px;">
            <formSubTitVue title="游戏选择"></formSubTitVue>
          </div>
          <el-form-item label="游戏名称" prop="gameId">
            <el-select filterable clearable v-model="form.gameId" placeholder="请选择游戏名称" @change="gameChange">
              <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="游戏区服" prop="qufuIds">
            <el-cascader @change="qufuChange" filterable clearable v-model="form.qufuIds" :options="qufuTree" :props="qufuProps"></el-cascader>
          </el-form-item>

          <div style="margin-bottom: 10px;">
            <formSubTitVue title="其他信息"></formSubTitVue>
          </div>
          <el-form-item label="加入监控" prop="monitorTaskId">
            <el-select filterable clearable v-model="form.monitorTaskId" placeholder="请选择监控任务">
              <el-option v-for="dict in taskList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>

          </el-form-item>
          <div class="tip">注意：只有QQ账号可以加入监控，其他类型账号请勿选择此项！</div>
          <!-- <el-form-item label="游戏账号" prop="accountNumber">
            <el-input v-model="form.accountNumber" placeholder="请输入游戏账号" />
          </el-form-item> -->
          <!-- <div style="margin-bottom: 10px;">
            <formSubTitVue title="其他选项"></formSubTitVue>
          </div>
          <el-form-item class="row" label="发布方式" prop="isAutoImg">
            <el-radio-group :disabled="autoImgDisabled" v-model="form.isAutoImg">
              <el-radio :label="1">手动发布</el-radio>
              <el-radio :label="2">快速发布</el-radio>
            </el-radio-group>
            <div style="line-height: 22px;color:#666" v-if="autoImgDisabled&&form.qufu">
              当前选择的游戏或大区不支持快速发布，目前仅支持部分游戏和大区快速发布！
            </div>
          </el-form-item> -->


          <div class="center" style="margin-top: 15px;">
            <el-button type="warning" plain @click="fabu(1)" v-loading="loading">手动发布</el-button>
            <el-button v-if="form.gameId&&isYingdiFlag" type="primary" plain @click="fabu(3)" v-loading="loading">
              <span v-if="form.gameId==2">营地获取</span>
              <span v-else-if="form.gameId==12||form.gameId==4">授权获取</span>
              <span v-else>扫码获取</span>
            </el-button>
            <el-button v-if="!autoImgDisabled" type="primary" @click="fabu(2)" v-loading="loading">自动截图发布</el-button>
            <!-- <el-button @click="closeFn()">取消</el-button>
            <el-button type="primary" @click="submitForm('form')" v-loading="loading">下一步</el-button> -->
          </div>
          <div class="shuoming">
            <p>说明：</p>
            <p>* 营地获取/扫码授权：使用营地扫码获取装备信息，并生成图片。1虞豆/次。  </p>
            <p>* 自动截图：使用账密登录游戏自动截图，识别装备信息生成文图； </p>
            <p style="padding-left: 80px;">  安卓端30虞豆/次；苹果端35虞豆/次 ；PC端40虞豆/次。</p>
          </div>
        </el-form>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import formSubTitVue from "@/views/tenantPages/components/formSubTit.vue";
import gameListApi from "@/api/gameConfig/gameList";
import checkPhoneApi from "@/api/gameConfig/checkPhonePx";
export default {
  name: "addGoodsBefore",
  components: {
    formSubTitVue,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!/^1[3-9][0-9]\d{8}$/.test(value)) {
        callback(new Error("手机号不正确!"));
      } else {
        callback();
      }
    };
    var priceReg = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!this.priceReg.test(value)) {
        callback(new Error("价格不正确!"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      isEdit: false,
      isView: false,
      isBackGoods: false,
      infoInputed: false, //是否已填写商品详情
      currentGame: {}, //当前选择的游戏
      goodsId: "",

      title: "发布商品",

      qufuSelect: [],
      qufuTree: [],
      qufuProps: {
        value: "id",
        label: "fieldName",
        children: "childGameAttributes",
        expandTrigger: "hover",
      },

      dialogVisible: false,
      btnLoading: false,
      gameList: [], //展示的游戏
      AllgameList: [], //所有游戏
      // 表单参数
      form: {
        gameId: "",
        qufu: "",
        gameName: "",
        isAutoImg: 1,
        gameType: "",
        qufuIds: [],
        monitorTaskId: "",
      },

      rules: {
        gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
        qufuIds: [{ required: true, message: "请选择区服", trigger: "change" }],
      },
      autoImgDisabled: false,
      taskList: [],

      infoByYdIds: [2, 3, 5, 6, 29, 16, 25,10,12,67,8,7], // 7,14 支持营地获取的游戏ID集合  12永劫  10火影 4原神 67三角洲 8枪战王者 7QQ飞车 14QQ飞车手游
      kuaisuIds: [2,  10, 12, 37, 34, 21, 8, 19, 4, 14, 11, 67,73], //支持小算自动截图的游戏ID集合 73燕云十六声
      isYingdiFlag:false,//是否可以使用营地获取
    };
  },
  created() {
    // this.headers = {
    //   Authorization: "Bearer " + getToken(),
    // };
    // this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    // this.uploadVideoUrl = process.env.VUE_APP_BASE_API + "/upload/video";
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
    
  },
  methods: {
    async open(flag, id) {
      //  console.log("%c Line:134 🍷 id", "color:#465975", id);
      this.dialogVisible = true;
      this.routename = "";
      this.getJiankongList();
      const isGame = await this.getGameList();
      if (!isGame) {
        return;
      }
      this.$nextTick(async () => {
        // window.removeEventListener("message", this.xiaosuanFn);
        this.fabuJingpai = false;
        this.isView = false;
        this.isEdit = false;
        this.isBackGoods = false;
        if (flag == "backOrder") {
          // 回收订单完成  发布商品
          this.title = "发布商品";
          // this.isEdit = true;
          // this.isBackGoods = true;
          // 回显游戏和区服
          let allData = JSON.parse(id.goodsContent);
          let qufuIds =
            allData.gameType == 1
              ? [allData.groupId, allData.serverId]
              : [
                  allData.systemId,
                  allData.carrierId,
                  allData.groupId,
                  allData.serverId,
                ];
          this.form.gameId = allData.gameId;
          await this.gameChange(this.form.gameId);
          this.form.qufuIds = qufuIds;
          this.qufuChange(qufuIds)
        } else if (flag == "jingpai") {
          //竞拍市场直接发布竞拍商品
          this.title = "发布竞拍商品";
          // this.fabuJingpai = true;
        } else {
          this.title = "新增游戏账号";
        }
      });
    },

    // 获取区服树结构
    async getQufuTree(gameId) {
      this.qufuTree = [];
      let obj = {};
      obj.gameId = gameId || this.form.gameId;
      try {
        const res = await gameListApi.qufuTreeGetByGameId(obj)
        this.qufuTree = [...res.data];
      } catch (error) {
        
      }
    },
    // 获取监控任务列表
    getJiankongList() {
      this.taskList = [];
      this.loading = true;
      this.$nextTick(() => {
        const paramsObj = {
          isPage: 2,
          type: 1,
        };
        checkPhoneApi
          .monitorTaskList(paramsObj)
          .then((response) => {
            this.loading = false;
            this.taskList = response.rows;
          })
          .catch((err) => {
            this.loading = false;
          });
      });
    },

    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getCustomGamelist();
      // ////console.log("%c Line:278 🍫 res", "color:#465975", res);
      this.gameList = res.data;
      if (this.gameList && this.gameList.length) {
        return true;
      } else {
        this.$confirm("你还未设置游戏，是否立即设置游戏？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.closeFn("GameSetting");
          })
          .catch(() => {
            this.closeFn();
          });
        return false;
      }
    },
    // 游戏选择改变
    async gameChange(e) {
      this.GetIsKuaiSu(e);
      if (this.form.qufu) {
        this.form.qufu = "";
      }
      this.currentGame = "";
      this.form.gameName = "";
      this.form.gameType = "";
      this.form.qufuIds = [];
      if (e) {
        
        for (let i = 0; i < this.gameList.length; i++) {
          if (this.gameList[i].id == e) {
            this.form.gameName = this.gameList[i].name;
            this.currentGame = this.gameList[i];
            this.form.gameType = this.gameList[i].type;
          }
        }
       await this.getQufuTree();
      }
    },
    // 判断游戏是否为营地获取的游戏
    isYingdi(){
      let result = false
      if(this.infoByYdIds.includes(this.form.gameId)){
        result = true
        if(this.form.gameId==67&&this.form.carrierId!=94175){
          result = false
          
        }
      }
      this.isYingdiFlag = result
    },
    // 判断游戏是否为可快速发布的游戏
    GetIsKuaiSu(id) {
      this.isYingdi()
      let result = this.kuaisuIds.includes(id);
      if (result) {
        // 一些游戏智能特定区服可以快速发布
        if (id == 3) {
          // 和平    安卓QQ区
          if (this.form.carrierId != 38838 || this.form.systemId != 38835) {
            result = false;
          }
        } else if (id == 2) {
          // 王者    QQ区
          if (this.form.carrierId != 38243) {
            result = false;
          }
        } else if (id == 10) {
          // 火影
          if (this.form.carrierId != 42198) {
            result = false;
          }
        } else if (id == 12) {
          // 永劫无间
          if (this.form.groupId != 55614) {
            result = false;
          }
        } else if (id == 37) {
          // 永劫无间手游
          if (this.form.carrierId != 79701) {
            result = false;
          }
        } else if (id == 34) {
          // 暗区突围
          if (this.form.carrierId != 71549) {
            result = false;
          }
        } else if (id == 21) {
          // 第五人格
          if (this.form.systemId != 42894 || this.form.carrierId != 42895) {
            result = false;
          }
        } else if (id == 8) {
          // 枪战王者
          if (this.form.systemId != 41538 || this.form.carrierId != 41541) {
            result = false;
          }
        } else if (id == 19) {
          // 使命召唤手游
          if (this.form.systemId != 45999 || this.form.carrierId != 46002) {
            result = false;
          }
        } else if (id == 14) {
          // QQ飞车手游
          if (this.form.systemId != 44030 || this.form.carrierId != 44032) {
            result = false;
          }
        } else if (id == 67) {
          // 三角洲行动
          if (this.form.carrierId != 94175) {
            result = false;
          }
        }else if (id == 73) {
          // 燕云十六声
          if (this.form.groupId != 99302) {
            result = false;
          }
        }
      }
      if (result) {
        // 启用快速发布
        this.autoImgDisabled = false;
      } else {
        // 禁用快速发布
        this.autoImgDisabled = true;
      }
      return result;
    },

    // 重置
    reset() {
      this.$refs["form"].resetFields();
    },
    // 区服改变
    qufuChange(e) {
      // console.log("%c Line:220 🍐 e", "color:#33a5ff", e);
      this.form.systemName = "";
      this.form.carrierName = "";
      this.form.groupName = "";
      this.form.serverName = "";
      
      this.form.systemId = "";
      this.form.carrierId = "";
      this.form.groupId = "";
      this.form.serverId = "";
      if (!e || e.length == 0) {
        this.GetIsKuaiSu(this.form.gameId);
      } else {
        this.getQufuForQufuIds();
      }
    },
    // 处理区服
    getQufuForQufuIds() {
      // 处理区服
      let qufu = "";
      if (this.currentGame.type == 1) {
        // 端游
        this.qufuTree.forEach((daqu) => {
          if (daqu.id == this.form.qufuIds[0]) {
            qufu += daqu.fieldName;
            this.form.groupId = daqu.id;
            this.form.groupName = daqu.fieldName;
            if (daqu.childGameAttributes && daqu.childGameAttributes.length) {
              daqu.childGameAttributes.forEach((fu) => {
                if (fu.id == this.form.qufuIds[1]) {
                  qufu += fu.fieldName;
                  this.form.serverId = fu.id;
                  this.form.serverName = fu.fieldName;
                }
              });
            }
          }
        });
      } else {
        // 手游
        this.qufuTree.forEach((sys) => {
          if (sys.id == this.form.qufuIds[0]) {
            qufu += sys.fieldName;
            this.form.systemId = sys.id;
            this.form.systemName = sys.fieldName;
            if (sys.childGameAttributes && sys.childGameAttributes.length) {
              sys.childGameAttributes.forEach((carr) => {
                if (carr.id == this.form.qufuIds[1]) {
                  qufu += carr.fieldName;
                  this.form.carrierId = carr.id;
                  this.form.carrierName = carr.fieldName;
                  if (
                    carr.childGameAttributes &&
                    carr.childGameAttributes.length
                  ) {
                    carr.childGameAttributes.forEach((daqu) => {
                      if (daqu.id == this.form.qufuIds[2]) {
                        qufu += daqu.fieldName;
                        this.form.groupId = daqu.id;
                        this.form.groupName = daqu.fieldName;
                        if (
                          daqu.childGameAttributes &&
                          daqu.childGameAttributes.length
                        ) {
                          daqu.childGameAttributes.forEach((fu) => {
                            if (fu.id == this.form.qufuIds[3]) {
                              qufu += fu.fieldName;
                              this.form.serverId = fu.id;
                              this.form.serverName = fu.fieldName;
                            }
                          });
                        }
                      }
                    });
                  }
                }
              });
            }
          }
        });
      }
      this.form.qufu = qufu;
      this.GetIsKuaiSu(this.form.gameId);
    },

    // 发布按钮
    fabu(type) {
      this.form.isAutoImg = type;
      this.submitForm();
    },
    // 提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$emit("next", JSON.parse(JSON.stringify(this.form)));
          this.closeFn();
        } else {
          this.$alert("请填写完整！");
        }
      });
    },

    closeFn(routename) {
      // if (routename) this.routename = routename;
      this.dialogVisible = false;
    },
    close() {
      this.reset();
      this.currentGame = "";
      this.qufuTree = [];
      this.form.qufuIds = [];
      this.$emit("close");
    },
  },
};
</script>
<style scoped lang="scss">
.tip {
  color: red;
}
.shuoming{
  color: #999;
  margin-top: 15px;
  p{
    margin: 5px 0;
  }
}
</style>
